package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmLoginDto dto) {
       //TODO
      //正常用户登录用户名跟密码
        if (!(StringUtils.isEmpty(dto.getName())&&StringUtils.isEmpty(dto.getPassword())) ){
            //根据用户名查询用户信息
            WmUser wmUser=getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName,dto.getName()));
            if (wmUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"用户信息不存在");
            }
            //1.2对比密码
            String salt = wmUser.getSalt();//获取用户的盐值
            String password = dto.getPassword();
            String paswd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if (!paswd.equals(wmUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //1.3返回数据
            String token = AppJwtUtil.getToken(wmUser.getId().longValue());
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", token);
            wmUser.setSalt("");
            wmUser.setPassword("");
            map.put("user", wmUser);
            return ResponseResult.okResult(map);
        }else {
            //游客登录
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }


}